import { Footer } from '@/components';
import {
  AlipayCircleOutlined,
  MailTwoTone,
  MobileTwoTone,
  TaobaoCircleOutlined,
  WeiboCircleOutlined
} from '@ant-design/icons';
import {
  CaptFieldRef,
  LoginForm,
  ProFormCaptcha,
  ProFormText
} from '@ant-design/pro-components';
import { Helmet, history, Link, useModel } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
// 全局?默认设置
import { getUserInfoUsingGet, sendCodeMockUsingPost, userLoginUsingPost } from '@/services/novel-web/userController';
import { MessageError, showNotification, ToLogin } from '@/utils/commonUtils';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    /**
     * @author aunsa
     */
    register: {

    }

  };
});

// 其他登录方式图标
const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
      <Link to="/user/register" className={styles.register}>
        注册账户
      </Link>
    </>
  );
};

// lang ->language, selectLang-> 选择语言
// const Lang = () => {
//   const { styles } = useStyles();

//   return (
//     <div className={styles.lang} data-lang>
//       {SelectLang && <SelectLang />}
//     </div>
//   );
// };

// 登录操作响应提醒Alert
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {

  // 用户登录状态
  // const [userLoginState, setUserLoginState] = useState<{status?:number}>({status:0});
  // 用户登录状态
  // const { status} = userLoginState;

  const { setInitialState, } = useModel('@@initialState');
  const { styles } = useStyles();

  const captchaRef = useRef<CaptFieldRef | null | undefined>();
  const [countDown, handleCountDown] = useState(10);




  const loadUserInfo = async () => {
    try {
      const req = await getUserInfoUsingGet();
      const { data: userInfo } = req;

      if (userInfo) {
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            currentUser: userInfo,
          }));
        });
      }
    } catch (error) {
      // 保存当前路径，跳转到登录页面
      ToLogin();
    }
  };

  const handleSendCode = async (phone: string) => {
    try {
      const respond = await sendCodeMockUsingPost({
        account: phone,
      });
      const { data: code } = respond;
      if (code && code.length != 0) {
        showNotification(code);
      }
    } catch (error: any) {
      MessageError(error);
      captchaRef.current?.endTiming();
    }

  };

  // 处理 login submit
  const handleLogin = async (values: API.UserLoginRequest) => {
    try {
      const respond = await userLoginUsingPost({
        account: values.account?.trim(),
        code: values.code?.trim(),
      });
      const { data: userToken } = respond;
      if (userToken && userToken.length != 0) {
        message.success('登录成功！');

        localStorage.setItem('userToken', userToken);

        await loadUserInfo();

        // 跳转回原页面
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
      }

    } catch (error: any) {
      MessageError(error);
    }
  };


  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'登录页'}
          - {Settings.title}
        </title>
      </Helmet>

      {/* 
      选择语言按钮
      <Lang /> 
      */}
      <br />

      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >

        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="Novel Web"
          subTitle={''}

          //submit按钮的文本设置
          submitter={{ searchConfig: { submitText: '登录', } }}

          //初始化变量默认值
          initialValues={{
            autoLogin: true,
          }}

          // actions={[
          //   <FormattedMessage
          //     key="loginWith"
          //     id="pages.login.loginWith"
          //     defaultMessage="其他登录方式"
          //   />,
          //   <ActionIcons key="icons" />,
          // ]}

          // 处理请求
          onFinish={async (values) => {
            await handleLogin(values as API.UserLoginRequest);
          }}

        >
          <Tabs
            // activeKey={type}
            // onChange={setType}
            centered
            items={[
              {
                key: 'login',
                label: '验证码登录',
              },
              // {
              //   key: 'admin',
              //   label: '管理员登录',
              // },
            ]}
          />

          {/* {status == -1 && type === 'login' && (
            <LoginMessage
              content={'账户或密码错误(root/root)'}
            />
          )} */}


          <>
            <ProFormText
              name="account"
              fieldProps={{
                size: 'large',
                prefix: <MobileTwoTone />,
              }}
              placeholder={'手机号: root'}

              rules={[
                {
                  required: true,
                  message: "请输入手机号!",
                },
                // {
                //   pattern: new RegExp(/^1[3-9]\d{9}$/, 'g'),
                //   message: '手机号格式不正确',
                // },
              ]}
            />

            <ProFormCaptcha
              name="code"
              phoneName="account"
              fieldRef={captchaRef}
              fieldProps={{
                size: 'large',
                prefix: <MailTwoTone />,
              }}
              countDown={countDown}
              captchaProps={{
                size: 'large',
              }}
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              placeholder='请输入验证码'
              onGetCaptcha={async (phone) => {
                handleSendCode(phone);
              }}
            />

          </>




          {/* 自动登录 忘记密码 */}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            {/* <ProFormCheckbox noStyle name="autoLogin">
              "自动登录"
            </ProFormCheckbox> */}
            {/* <a
              style={{
                float: 'right',
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
            </a> */}
          </div>

        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
